package com.fqy.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fqy.gmall.common.cache.GmallCache;
import com.fqy.gmall.common.constant.RedisConst;
import com.fqy.gmall.common.result.Result;
import com.fqy.gmall.model.product.*;
import com.fqy.gmall.product.mapper.*;
import com.fqy.gmall.product.service.ManageService;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * User: fqy
 * Date: 2021/9/8
 * Time: 9:22
 * Describe: 注意注意！！！根据业务区分service层 是对表进行操作 还是对对象也进行了操作，
 */
@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    //Spu
    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SpuPosterMapper spuPosterMapper;

    //skuImageList skuAttrValueList skuSaleAttrValueList
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    //查询一级目录
    @Override
    public List<BaseCategory1> getCategory1() {
        List<BaseCategory1> baseCategory1List = baseCategory1Mapper.selectList(null);
        return baseCategory1List;
    }

    //查询二级目录
    @Override
    public List<BaseCategory2> getCategory2(long category1Id) {
        QueryWrapper<BaseCategory2> baseCategory2QueryWrapper = new QueryWrapper<>();
        baseCategory2QueryWrapper.eq("category1_id", category1Id);
        List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(baseCategory2QueryWrapper);
        return baseCategory2List;
    }

    //查询三级目录
    @Override
    public List<BaseCategory3> getCategory3(long category2Id) {
        List<BaseCategory3> baseCategory3List = baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id", category2Id));
        return baseCategory3List;
    }

    //根据分类Id 获取平台属性数据
    @Override
    public List<BaseAttrInfo> getAttrInfoListById(Long category1Id, Long category2Id, Long category3Id) {
        //使用到了动态sql 关联查询 故需自己定义xml
        List<BaseAttrInfo> baseAttrInfoList = baseAttrInfoMapper.selectAttrInfoList(category1Id, category2Id, category3Id);
        return baseAttrInfoList;
    }

    //更新：保存修改或新增后的属性信息以其属性值
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //获取id 根据id有无判断添加和修改
        if(baseAttrInfo.getId() != null){
            //有id修改 ！！！ 注意这里的update是操作 info 表
            baseAttrInfoMapper.updateById(baseAttrInfo);
        }else{
            //无id添加
            baseAttrInfoMapper.insert(baseAttrInfo);
        }
        /**
         * 接下来再对value表进行操作
         * base_attr_value 先删除，再新增！
         * delete from base_attr_value where attr_id = ?;
         * 注意：此处删除的是value值表的数据 并非对baseAttrInfo对象进行删除
         */
        QueryWrapper<BaseAttrValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id",baseAttrInfo.getId());
        baseAttrValueMapper.delete (queryWrapper);
//        System.out.println("1111111111111111111111");
//        System.out.println(baseAttrInfo);
//        System.out.println("1111111111111111111111");
        /**
         * 保存 获取平台属性值集合数据
         */
        //由于填写或修改后的表单没有直接显示AttrValue的id 所以得获取AttrInfo中包含AttrValue的id 然后再设置
        //每个AttrInfo中包含多个 AttrValue 1对n的关系 所以需要遍历设置属性值的id
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
//        System.out.println("---------------------");
//        System.out.println(attrValueList);
//        System.out.println("---------------------");
        for (BaseAttrValue baseAttrValue : attrValueList) {
            // attrId 传递的时候是null
//            System.out.println(baseAttrValue);
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            baseAttrValueMapper.insert(baseAttrValue);
        }
    }
    //更新：根据平台属性Id 获取到平台属性值集合
    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        List<BaseAttrValue> attrValueList = baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id", attrId));
        return attrValueList;
    }

    @Override
    public BaseAttrInfo getBaseAttrInfo(Long attrId) {
        //  select * from base_attr_info where id = attrId;
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        //  如果有该平台属性信息
        if (baseAttrInfo != null){
            //再根据平台属性Id 获取到平台属性值集合
            List<BaseAttrValue> attrValueList = this.getAttrValueList(attrId);
            //把结果封装到BaseAttrInfo类中
            baseAttrInfo.setAttrValueList(attrValueList);
        }
        return baseAttrInfo;
    }
    //根据分类id查询spuInfo 获取spu分页显示列表
    @Override
    public IPage getSpuInfoPage(Page iPage, SpuInfo spuInfo) {
        //select * from spu_info where category3_id = 61 order by id limit 0 , 10;
        QueryWrapper<SpuInfo> spuInfoQueryWrapper = new QueryWrapper<>();
        spuInfoQueryWrapper.eq("category3_id", spuInfo.getCategory3Id());
        spuInfoQueryWrapper.orderByDesc("id");
        Page page = spuInfoMapper.selectPage(iPage, spuInfoQueryWrapper);
        return page;
    }

    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        //select * from base_sale_attr;
        return baseSaleAttrMapper.selectList(null);
    }
    //添加spu数据大保存

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {

         /*
            spuInfo;	商品表
            spuImage;	商品图片表
            spuSaleAttr;	销售属性
            spuSaleAttrValue;	销售属性值
            spuPoster;	商品海报
         */
        //保存spuInfo;商品表
        spuInfoMapper.insert(spuInfo);
        //保存spuImage商品图片
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)) {
            spuImageList.stream().forEach(spuImage->{
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            });
        }
        //保存spuPoster商品海报
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        if (!CollectionUtils.isEmpty(spuPosterList)) {
            spuPosterList.stream().forEach(spuPoster->{
                spuPoster.setSpuId(spuInfo.getId());
                spuPosterMapper.insert(spuPoster);
            });
        }
        //保存spuSaleAttr销售属性
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)) {
            spuSaleAttrList.stream().forEach(spuSaleAttr->{
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);
                //  获取销售属性值集合
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                    spuSaleAttrValueList.stream().forEach(spuSaleAttrValue -> {
                        //  赋值
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }
            });
        }
    }

    //根据spuId 获取spuImage 集合
    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        List<SpuImage> spuImageList = spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id", spuId));
        return spuImageList;
    }

    //根据spuid 回显销售属性，销售属性值！
    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        List<SpuSaleAttr> spuSaleAttrList = spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
        return spuSaleAttrList;
    }
    //添加sku之保存：保存skuInfo
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {
        skuInfoMapper.insert(skuInfo);
        //保存sku图片信息
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)) {
            skuImageList.stream().forEach(skuImage->{
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            });
        }
        //保存skuAttrValueList
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)) {
            skuAttrValueList.stream().forEach(skuAttrValue -> {
                skuAttrValue.setSkuId(skuInfo.getId());
                //  应该能够获取到平台属性名，平台属性值名！
                //  应该页面自动获取！
                //  查询：category3Id 查询到平台属性名！但是绝对找不到要给的属性值名称！
                //  经过分析：可以不用赋值attrName valueName;
                skuAttrValueMapper.insert(skuAttrValue);
            });
        }

        //保存SkuSaleAttrValue
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)) {
            skuSaleAttrValueList.stream().forEach(skuSaleAttrValue -> {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            });
        }

    }
    //商品属性skuInfo分页显示
    @Override
    public IPage<SkuInfo> getSkuInfoPage(Long page, Long limit) {
        Page<SkuInfo> skuInfoPage = new Page<>(page, limit);
        QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
        skuInfoQueryWrapper.orderByDesc("id");
        return skuInfoMapper.selectPage(skuInfoPage, skuInfoQueryWrapper);
    }

    //上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);
    }

    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);
    }

    //商品详情:获取skuInfo 基本信息+ skuImage图片列表！
    @Override
    @GmallCache(prefix = RedisConst.SKUKEY_PREFIX)
    public SkuInfo getSkuInfo(Long skuId) {
        return getSkuInfoDB(skuId);
    }

    private SkuInfo getSkuInfoByRedisson(Long skuId) {
        /**
         * 如果缓存里有=》查缓存  没有=》查DB
         * 定义缓存key sku:skuId:info
         * 使用redission锁
         */
        try {
            String skuKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKUKEY_SUFFIX;
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
            //判断缓存里是否有数据
            if (skuInfo==null){
                String lockKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKULOCK_SUFFIX;
                //缓存里没有=》查DB+加锁！
                //上锁
                RLock lock = redissonClient.getLock(lockKey);
                //  加上锁
                boolean result = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                if (result){

                    try {
                        //  业务逻辑
                        skuInfo = getSkuInfoDB(skuId);
                        //防止缓存穿透 给该值对应的缓存中设置为null
                        if (skuInfo == null) {
                            //数据库中没有的话
                            SkuInfo skuInfo1 = new SkuInfo();
                            this.redisTemplate.opsForValue().set(skuKey, skuInfo1 ,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                            return skuInfo1 ;
                        }else {
                            //数据库中有数据
                            this.redisTemplate.opsForValue().set(skuKey,skuInfo ,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS );
                        }
                        return skuInfo;
                    } finally {
                        //  解锁
                        lock.unlock();
                    }

                }else{
                //  没有获取到锁的人！
                    try {
                        Thread.sleep(100);
                        return getSkuInfo(skuId);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }else{
                //  缓存中有数据直接返回
                return skuInfo;
            }
        } catch (InterruptedException e) {
            //  记录日志.....
            e.printStackTrace();
        }
        return getSkuInfoDB(skuId);
    }

    public SkuInfo getSkuInfoByRedisLua(Long skuId) {
        /**
         * 如果缓存里有=》查缓存  没有=》查DB
         * 定义缓存key sku:skuId:info
         * 使用Lua+redis 锁
         */
        try {
            String skuKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKUKEY_SUFFIX;
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
            //判断
            if (skuInfo==null){
                //缓存里没有=》查DB+加锁！
                String uuid = UUID.randomUUID().toString();
                String lockKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKULOCK_SUFFIX;
                Boolean flag = this.redisTemplate.opsForValue().setIfAbsent(lockKey, uuid, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                //flag 为 true 说明里面没有锁！  不存在   生效
                if (flag) {
                //业务逻辑
                    skuInfo = getSkuInfoDB(skuId);
                    //防止缓存穿透 给该值对应的缓存中设置为null
                    if (skuInfo == null) {
                        //数据库中没有的话
                        /**
                         * 注意体会 设置为null（出现熔断 缓存内空） 和设置 skuInfo1（没有熔断 缓存为空对象）的区别
                         */
    //                    this.redisTemplate.opsForValue().set(skuKey, null,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
    //                    return skuInfo;
                        SkuInfo skuInfo1 = new SkuInfo();
                        this.redisTemplate.opsForValue().set(skuKey, skuInfo1 ,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                        return skuInfo1 ;
                    }else {
                        //数据库中有数据
                        this.redisTemplate.opsForValue().set(skuKey,skuInfo ,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS );
                    }

                    //注意释放锁
                    //  定义一个lua 脚本
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                    //  准备执行lua 脚本
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                    //  将lua脚本放入DefaultRedisScript 对象中
                    redisScript.setScriptText(script);
                    //  设置DefaultRedisScript 这个对象的泛型
                    redisScript.setResultType(Long.class);
                    //  执行删除
                    redisTemplate.execute(redisScript, Arrays.asList("lock"), uuid);
                } else {
                    //flag 为 false 存在 不生效！ del key! false
                    try {
                        Thread.sleep(200);
                        //  自旋
                        return getSkuInfo(skuId);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }else{
                //缓存中有数据直接返回
                return skuInfo;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        //  表示获取数据库中的数据！
        return getSkuInfoDB(skuId);
    }

    /**
     * 从数据库中获取数据
     * @param skuId
     * @return
     */
    private SkuInfo getSkuInfoDB(Long skuId) {
        // 获取skuInfo 基本信息
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        // 获取skuImage图片列表 ??? 为啥图片可以一起传
        //  判断skuInfo 是否为空！
        if (skuInfo !=null) {
            List<SkuImage> skuImages = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
            skuInfo.setSkuImageList(skuImages);
        }
        return skuInfo;
    }

    /**
     * 商品详情:获取商品价格数据 注意价格不需要放到缓存
     * @param skuId
     * @return
     */
    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        //select price from sku_info where id = skuId;
        RLock lock = redissonClient.getLock(skuId + ":lock");
        //  上锁
        lock.lock();
        SkuInfo skuInfo = null;
        BigDecimal price = new BigDecimal(0);
        try {
            QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
            skuInfoQueryWrapper.eq("id", skuId);
            skuInfoQueryWrapper.select("price");
            skuInfo = skuInfoMapper.selectOne(skuInfoQueryWrapper);
            if(skuInfo!=null){
                price = skuInfo.getPrice();
            }
        }finally {
            lock.unlock();
        }
        //  返回价格
        return price;
    }
    //商品详情:根据三级分类Id 来获取分类名称等数据
    @Override
    @GmallCache(prefix = "CategoryView:")
    public BaseCategoryView getCategoryName(Long category3Id) {
        //category3Id 哪里来？ skufo.getcategory3Id
        return baseCategoryViewMapper.selectById(category3Id);
    }
    // 商品详情:根据spuId,skuId 来获取销售信息
    @Override
    @GmallCache(prefix = "SpuSaleAttrList:ById")
    public List<SpuSaleAttr> getSpuSaleAttrListById(Long skuId, Long spuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrListById(skuId,spuId);
    }
    // 商品详情:根据用户所选的销售属性组合 进行页面切换
    @Override
    @GmallCache(prefix = "ValueIdsAndSkuIdToMap:")
    public Map getValueIdsAndSkuIdToMap(Long spuId) {
        //  声明map 集合
        HashMap<Object, Object> hashMap = new HashMap<>();
        //  获取销售属性值Id 与skuId ！
        //  执行sql 语句获取到 List<Map> mapList
        //  为什么返回值是这？？？重点！！！
        //  答;对比 select * from base_category1; List<BaseCategory1>  base.setName(name);
        List<Map> mapList = skuSaleAttrValueMapper.selectValueIdsAndSkuIdToMap(spuId);
        if (!CollectionUtils.isEmpty(mapList)) {
            mapList.stream().forEach(map -> {
                hashMap.put(map.get("value_ids"),map.get("sku_id"));
            });
        }
        return hashMap;
    }
    // 商品详情:根据spuId 来获取海报信息集合
    @Override
    @GmallCache(prefix = "SpuPosterList:")
    public List<SpuPoster> getSpuPosterList(Long spuId) {
        //  select * from spu_poster where spu_id = spuId;
        List<SpuPoster> spuPosters = spuPosterMapper.selectList(new QueryWrapper<SpuPoster>().eq("spu_id", spuId));
        return spuPosters;
    }
    // 商品详情:获取商品的规格参数：获取商品的平台属性平台属性值！
    @Override
    @GmallCache(prefix = "BaseAttrInfoList:")
    public List<BaseAttrInfo> getBaseAttrInfoList(Long skuId) {
        return baseAttrInfoMapper.selectBaseAttrInfoList(skuId);
    }

    // 商品首页:获取全部分类信息
    @Override
    @GmallCache(prefix = "BaseCategoryList")
    public List<JSONObject> getBaseCategoryList() {
        //  声明一个集合
        List<JSONObject> list = new ArrayList<>();
        //  一级，二级，三级分类数据！
        //  获取到所有的分类数据  base_category_view
        List<BaseCategoryView> baseCategoryViews = baseCategoryViewMapper.selectList(null);
        //  分组：先按照一级分类Id 进行分组！
        //  map key = category1Id  value = List<BaseCategoryView>
        Map<Long, List<BaseCategoryView>> baseCategory1Map = baseCategoryViews.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        //  声明一个index 遍历
        int index = 1;
        //  循环遍历这个map集合
        Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = baseCategory1Map.entrySet().iterator();
        while (iterator.hasNext()) {
            //  创建一个对象
            JSONObject category1 = new JSONObject();
            //  获取到 Entry 对象
            Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
            Long category1Id = entry.getKey();
            List<BaseCategoryView> baseCategoryViewList1 = entry.getValue();
            //  一级分类Id
            category1.put("categoryId",category1Id);
            //  一级分类名称
            category1.put("categoryName",baseCategoryViewList1.get(0).getCategory1Name());
            //  表示一级分类的第几项！
            category1.put("index",index);
            //  一级分类下还有categoryChild ，必须知道二级分类数据集合！
            //  index 迭代！
            index++;
            //  获取一级分类下的二级分类数据！
            //  key = category2Id value = List<BaseCategoryView>
            Map<Long, List<BaseCategoryView>> baseCategory2Map = baseCategoryViewList1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            //  循环遍历
            Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = baseCategory2Map.entrySet().iterator();
            //  声明一个存储二级分类数据的集合
            List<JSONObject> category2Child = new ArrayList<>();
            while (iterator1.hasNext()) {
                //  创建一个对象
                JSONObject category2 = new JSONObject();
                //  获取到 Entry 对象
                Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator1.next();
                Long category2Id = entry1.getKey();
                List<BaseCategoryView> baseCategoryViewList2 = entry1.getValue();
                //   赋值二级分类Id
                category2.put("categoryId",category2Id);
                //  赋值二级分类name
                category2.put("categoryName",baseCategoryViewList2.get(0).getCategory2Name());
                //  存储二级分类数据
                category2Child.add(category2);
                //  创建一个集合来存储三级分类数据
                List<JSONObject> category3Child = new ArrayList<>();
                //  获取三级分类数据：
                baseCategoryViewList2.forEach(baseCategoryView->{
                    //  创建一个对象
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId",baseCategoryView.getCategory3Id());
                    category3.put("categoryName",baseCategoryView.getCategory3Name());
                    category3Child.add(category3);
                });
                //  将三级分类数据保存到二级分类数据中
                category2.put("categoryChild",category3Child);
            }
            //  将二级分类数据保存到一级分类数据中
            category1.put("categoryChild",category2Child);
            //  将一级分类数据添加到集合中
            list.add(category1);
        }
        //  返回数据
        return list;
    }


}
